<?php
namespace app\common\controller;
use app\common\controller\Base;
use think\Request;
use think\Config;
use app\common\model\Member;
use app\common\model\PhoneCode;
use think\Cache;
use think\Log;
class Api extends Base
{
//    use \app\common\traits\Curd;
    
    protected $logicClass;
    protected $modelClass;
    protected $authenticate; // 身份验证
    protected $allowAction;  //允许访问的方法,比如user
    protected $accessToken;  // token
    protected $userId;
    
    protected $key = 'bd514c52-5363-4364-b73f-a2ec93ae6b34';
    protected $successCode;
    protected $successMsg;
    protected $errorCode;
    protected $errorMsg;
    
    
    /**
     * 初始方法
     */
    
    protected function _initialize()
    {
        
        if ($_SERVER['REQUEST_METHOD']=='OPTIONS') {
            header("Access-Control-Allow-Origin: *");
            header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization");
            header('Access-Control-Allow-Methods: GET, POST, PUT,DELETE,OPTIONS,PATCH');
            return;
        }
        
        $this->successCode = Config::get('success_code');
        $this->successMsg = Config::get('success_msg');
        $this->errorCode = Config::get('error_code');
        $this->errorMsg = Config::get('error_msg');
        
        
        $request = Request::instance();
        $this->accessToken = $request->header('access-token');
        
        $action = strtolower($request->action());

//        if ($this->allowAction) {
//            if(!in_array($action,$this->allowAction)){
//                $rt = [
//                    'action'=>$action,
//                    'allow'=>$this->allowAction
//                ];
//                api(101, "该方法不允许访问！",$rt);
//            }
//        }
        
        //指定哪些方法需要登陆，后面要替换掉auth

        if ($this->authenticate) {
            $this->beforeActionList['authenticate'] = $this->authenticate;
        } else {
            $this->beforeActionList['authenticate'] = null;//为null的话默认所有接口都要权限
        }
        
        
        if ($this->modelClass == null) {
            //去掉控制器后面的Controller
            $modelName = str_replace("Controller","",Request::instance()->controller());
            $this->modelClass = 'app\common\model\\'.ucfirst(preg_replace('/[^>]+\./','',$modelName));//默认model
            $this->logicClass = 'app\common\logic\\'.ucfirst(preg_replace('/[^>]+\./','',$modelName)).'Logic';//默认model
        }
        
    }
    
    /**
     *  鉴定身份
     */
    protected function authenticate()
    {
        if ($this->accessToken == null) {
            Log::info('token expire 111111111111111');
            api($this->errorCode['token_required'],$this->errorMsg['token_required'],null);
        }
        
        //正好token和cache都是一周过期
        $userId= Cache::get($this->accessToken);
        
        if ($userId) {
            $member = Member::get($userId);
            if(!$member){
                Log::info('token expire 222222222222222');
                api($this->errorCode['token_required'],$this->errorMsg['token_required'],null);
            }
        }else{
            Log::info('token expire 333333333333333');
            api($this->errorCode['token_required'],$this->errorMsg['token_required'],null);
        }
        
    }
    
    protected function getUserInfo(){
        
        $userInfo = Member::get(Cache::get($this->accessToken));
        if(isset($userInfo)){
            return $userInfo;
        }else{
            return null;
        }
        
    }
    
    protected function getUserId(){
        
        $userId = Cache::get($this->accessToken);
        
        if(!$userId){
            api($this->errorCode['token_required'],$this->errorMsg['token_required'],null);
            Log::info('token expire 333333333333333');
        }else{
            return $userId;
        }
        
    }
    
    
    /**
     * @desc 校验验证码是否正确
     * @param $BizId
     * @param $code
     * @return bool
     * @throws \think\exception\DbException
     */
    function checkPhoneCode($BizId,$code){
        $phoneCode = PhoneCode::get(['BizId'=>$BizId]);
        
        if(!isset($phoneCode)){
            error('短信回执参数错误');
        }
        
        if($phoneCode->code&&$phoneCode->code==$code){
            //五分钟过期
            if(strtotime($phoneCode->create_time)<(time()-5*60)){
                
                error('验证码过期');
            }
            return true;
        }else{
            error('验证码输入错误');
        }
    }
    
    
    
    /**
     * 列表
     */
    public function index()
    {
        $params = paramForm();
        
        //如果有id参数，则表示获取单个
        if(isset($params['id'])){
            $this->read($params);
            die;
        }
        
        $logicClass = $this->logicClass;
        $logic = new $logicClass();
       
        $lists = $logic->getList($params);
        if($lists){
            success($lists);
        }else{
            error('没有符合的数据');
        }
        
    }
    
    public function read($params)
    {

        $logicClass = $this->logicClass;
        $logic = new $logicClass();
       
        $logic->setSql($params);
       
        $one = $logic->findModel();
        if($one){
            success($one);
        }else{
            error('数据不存在或者无权限查看');
        }
        
    }
    
    
//    /**
//     * 列表（分页）
//     */
//    public function index(){
//        $list = $this->prepareDataProvider();
//        success($list->toArray());
//    }
//
//    /**
//     * 详情
//     */
//    public function read($id){
//        $model = $this->findModel($id);
//        if($model){
//            success($model);
//        }else{
//            error("没有该ID的结果记录哦！");
//        }
//
//    }
//
//    /**
//     * 保存（新增）
//     */
//    public function save(){
//
//        $param = $_POST;
//        if($param == null)$param = json_decode(file_get_contents("php://input"),true);
//        if($param == null)error("你没有提交参数哦！");
//
//        $modelClass = $this->modelClass;
//        $model = new $modelClass($param);
//        $model->allowField(true)->save();
//
//        if($model){
//            success($model);
//        }else{
//            error($model->getError());
//        }
//    }
//
//    /**
//     * 修改
//     */
//    public function update($id){
//
//        $param = $_POST;//如果能用put就好了  request()->put()
//        if($param == null)error("你没有提交参数哦！");
//
//        $modelClass = $this->modelClass;
//        $this->condition['id']=$id;
//        $m = new $modelClass();
//        $rt = $m ->allowField(true)->save($param, $this->condition);
//        if($rt){
//            success($m);
//        }else{
//            error("修改失败，你有可能没有修改任何参数！".$m->getError());
//        }
//    }
//
    /**
     * 删除
     */
    public function delete($id){

        $modelClass = $this->modelClass;
        $this->condition['id']=$id;
        $rt = $modelClass::destroy($this->condition);
        if($rt){
            success();
        }else{
            error($modelClass->getError);
        }
    }
    
    
    /**
     * 重写 表单验证
     */
    protected function validate($data, $validate, $message = [], $batch = false, $callback = null)
    {
        $result = parent::validate($data, $validate, $message, $batch, $callback); // TODO: Change the autogenerated stub
        if (true !== $result) {
            error($result);
        }
    }
    
    /**
     * 按场景验证
     * @param $data 验证数据
     * @param null $name 场景名
     */
    protected function validateByScene1($data,$name)
    {
        $validate = new Validate($this->rule);
        $validate->scene($name, $this->scene[$name]);
        $validate->message($this->msg);
        $result = $validate->scene($name)->check($data);
        if (true !== $result) {
            error($validate->getError());
        }
    }
    
    protected function setPost($params,$filed=''){
        $arr = [];
        foreach ($params as $key=>$value){
            if(strpos($filed,$key)>-1){
                $arr[$key] = $value;
            }
        }
        return $arr;
    }
    
    
    
    
}